<template>
  <Category :scene="scene" />
  <el-card style="margin: 10px 0">
    <div v-show="scene === 0">
      <el-button
        type="primary"
        icon="plus"
        :disabled="!categoryStore.category3Id"
        @click="addAttr"
        v-has="`btn.Attr.add`"
      >
        添加平台属性
      </el-button>
      <el-table :data="attrList" border style="margin: 10px 0">
        <el-table-column
          label="序号"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column
          label="属性名称"
          width="120px"
          prop="attrName"
        ></el-table-column>
        <el-table-column label="属性值">
          <template #default="scope">
            <el-tag
              v-for="item in scope.row.attrValueList"
              :key="item.id"
              style="margin: 5px 5px"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              icon="edit"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>

            <el-popconfirm
              :title="`确认删除属性：${scope.row.attrName}?`"
              @confirm="handleDelete(scope.row)"
              cancel-button-text="取消"
              confirm-button-text="确认"
              width="200"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="scene === 1">
      <el-form :inline="true">
        <el-form-item label="属性值名称">
          <el-input
            v-model="attrInfo.attrName"
            placeholder="请输入属性名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <div style="margin: 10px 0">
        <el-button
          @click="addAttrValue"
          icon="plus"
          type="primary"
          :disabled="!attrInfo.attrName.trim()"
        >
          添加属性
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
      <el-table border :data="attrInfo.attrValueList">
        <el-table-column
          label="序号"
          width="80"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #default="{ row, $index }">
            <el-input
              :ref="(el: any) => handler($index, el)"
              v-if="row.isEdit"
              @blur="toView(row, $index)"
              v-model="row.valueName"
              placeholder="请输入属性值名称"
            ></el-input>
            <div v-if="!row.isEdit" @click="toEdit(row, $index)">
              {{ row.valueName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ $index }">
            <el-button type="danger" size="small" @click="delAttrValue($index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 10px 0">
        <el-button
          type="primary"
          @click="saveAttr"
          :disabled="attrInfo.attrValueList.length === 0"
        >
          保存
        </el-button>
        <el-button type="primary">取消</el-button>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts" name="attr">
import useCategoryStore from '@/store/modules/category.ts'
import {
  reqGetAttr,
  reqSaveAttr,
  reqDeleteAttr,
} from '@/api/product/attr/index.ts'
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import type {
  AttrList,
  AttrObj,
  AttrValueObj,
} from '@/api/product/attr/type.ts'
import { ElMessage } from 'element-plus'
const attrList = ref<AttrList>([])
const categoryStore = useCategoryStore()
const attrInfo = reactive<AttrObj>({
  categoryId: '',
  attrName: '',
  categoryLevel: 3,
  attrValueList: [],
})
watch(
  () => categoryStore.category3Id,
  async (newVal) => {
    attrList.value = []
    if (newVal) {
      getAttrList()
    }
  },
)
const getAttrList = async () => {
  const { category1Id, category2Id, category3Id } = categoryStore
  const res = await reqGetAttr(category1Id, category2Id, category3Id)
  console.log('属性数据===>', res)
  if (res.code === 200) {
    attrList.value = res.data
  }
}
// 编辑属性
const handleEdit = (row: Attr) => {
  scene.value = 1
  console.log('编辑属性===>', row)
  //将属性对象赋值给attrInfo
  //需要深拷贝
  Object.assign(attrInfo, JSON.parse(JSON.stringify(row)))
}
//保存属性
const saveAttr = async () => {
  attrInfo.categoryId = categoryStore.category3Id
  const res = await reqSaveAttr(attrInfo)
  console.log('保存属性===>', res)
  if (res.code === 200) {
    ElMessage.success(attrInfo.id ? '修改成功' : '添加成功')
    scene.value = 0
    //查询属性值
    getAttrList()
  } else {
    ElMessage.error(attrInfo.id ? '修改失败' : '添加失败')
  }
}
// 删除属性
const handleDelete = async (row: AttrObj) => {
  console.log('删除属性===>', row)
  const res = await reqDeleteAttr(row.id as number)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    getAttrList()
  } else {
    ElMessage.error('删除失败')
  }
}
//定义card组件内容切换变量
let scene = ref<number>(0)
// 添加属性
const addAttr = () => {
  scene.value = 1
  //清空属性对象
  Object.assign(attrInfo, {
    categoryId: categoryStore.category3Id,
    attrName: '',
    categoryLevel: 3,
    attrValueList: [],
  })
}
// 取消
const cancel = () => {
  scene.value = 0
}
// 添加属性值
const addAttrValue = () => {
  attrInfo.attrValueList.push({
    valueName: '',
    attrId: categoryStore.category3Id,
    isEdit: true,
  })

  //获取元素的input实例
  nextTick(() => {
    //获取最后一个属性值元素实例
    let last = inputArr.value[attrInfo.attrValueList.length - 1]
    //聚焦
    last.focus()
  })
}
// 删除属性值
const delAttrValue = (index: number) => {
  attrInfo.attrValueList.splice(index, 1)
}
//定义一个响应式数据控制属性值查看和编辑模式的切换
const toView = (data: AttrValueObj, $index: number) => {
  //属性值为空
  if (data.valueName.trim() === '') {
    attrInfo.attrValueList.splice($index, 1)
    ElMessage.error('属性值不能为空')
    return
  }
  //属性值不能相同
  let repeat = attrInfo.attrValueList.find((item) => {
    if (item != data) {
      return item.valueName === data.valueName
    }
  })
  if (repeat) {
    ElMessage.error('属性值不能重复')
    return
  }
  data.isEdit = false
}
const toEdit = (data: AttrValueObj, $index: number) => {
  data.isEdit = true
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
//准备一个数组：存储对应input组件实例
let inputArr = ref<any>([])
const handler = ($index: any, element: any) => {
  console.log($index, element)
  inputArr.value[$index] = element
}

//路由组件切换销毁时，清空分类仓库数据
onBeforeUnmount(() => {
  // 清空分类仓库数据
  categoryStore.$reset()
})
</script>

<style scoped lang="scss"></style>
